import React, { useEffect } from "react";
import { Modal, Form, Input, message } from "antd";

interface IProps {
    open: boolean;
    data: any;
    onClose: () => void;
    dispatch: (arg: any) => any,
    refresAdmin: any
}

const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 12 },
      md: { span: 16 },
    },
  };

const EditAdminModal = (props: IProps) => {
    const { open, data, onClose, dispatch, refresAdmin } = props;
    const [form] = Form.useForm();


    useEffect(() => {
        if(open && data) {
            form.setFieldsValue({
                accountName: data.accountName,
                mail: data.mail,
            })
        }
    }, [open, data])

    const onOk = async () => {
        let values = await form.validateFields();
        dispatch({
            type: 'tenant/postObjWithRes',
            payload: {
              url: '/account/manage/edit',
              sid: data.sid,
              mail: values.mail,
            },
            callback: (response: any) => {
                if (response.statusCode === '0') {
                  message.success('保存成功');
                  onCancel();
                  refresAdmin();
                } else {
                  message.error(response.statusMessage);
                }
            },
        })
    }

    const onCancel = () => {
        form.resetFields();
        onClose();
    }

    return (
        <Modal
            title= "编辑管理员"
            open={open}
            onOk={onOk}
            onCancel={onCancel}
            okText="提交"
        >
            <Form form={form} {...formItemLayout}>
                <Form.Item
                    name='accountName'
                    label='登录账号'
                    rules={[
                        { required: true, message: '请输入邮箱' }
                    ]}
                >
                    <Input disabled />
                </Form.Item>
                <Form.Item
                    name='mail'
                    label='邮箱'
                    hasFeedback
                    rules={[
                        { required: true, message: '请输入邮箱' },
                        { type: 'email', message: '邮箱格式错误' }
                    ]}
                >
                    <Input maxLength={30} />
                </Form.Item>    
            </Form>
        </Modal>
    )
}

export default EditAdminModal;